package com.lxd.api.controller;

import com.lxd.common.constants.RabbitMQConstants;
import com.lxd.common.enums.smsCodeEnum;
import com.lxd.api.filter.CheckFilterContext;
import com.lxd.api.pojo.SingleSendForm;
import com.lxd.api.utils.R;
import com.lxd.api.vo.ResultVo;
import com.lxd.common.model.StandardSubmit;
import com.lxd.common.utils.SnowFlakeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @Author Dongdong
 * @注释 单条短信发送接口
 *
 */

@RestController
@Slf4j
@RequestMapping("/sms")
public class SmsController {
    @Autowired
    private CheckFilterContext context;

    @Autowired
    private SnowFlakeUtil snowFlakeUtil;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostMapping(value = "/single_send", produces = "application/json;charset=utf-8")
    public ResultVo singleSend(@RequestBody @Validated SingleSendForm singleSendForm, BindingResult bindingResult
            , HttpServletRequest request) {


        //1.参数校验出错
        if (bindingResult.hasErrors()) {
            //提取错误信息
            String msg = bindingResult.getFieldError().getDefaultMessage();
            System.out.println(msg);
            //记入日志中
            log.info("【接口模块-单挑短信Controller】 参数不合法！msg={}", msg);
            //返回
            return R.error(smsCodeEnum.PARAMETER_ERROR.getCode(), msg);
        }

//       封装StanderSubmit
        StandardSubmit submit = new StandardSubmit();
        submit.setApikey(singleSendForm.getApikey());
        submit.setIp(getRealIP(request));
        submit.setMobile(singleSendForm.getMobile());
        submit.setText(singleSendForm.getText());
        submit.setUid(singleSendForm.getUid());
        submit.setState(singleSendForm.getState());


//      接口模块校验！！
        context.check(submit);

//        生成分布式ID
        submit.setSequenceId(snowFlakeUtil.nextId());
//        设置短信发送时间
        submit.setSendTime(LocalDateTime.now());
//        发送到mq，交给策略模块
        /**
         *  rabbitTemplate.convertAndSend(RabbitMQConstants.SMS_PRE_SEND,队列名称
         *                                submit,消息
         *                                new CorrelationData(submit.getSequenceId().toString()));标识信息，可以知道哪个发送失败
         */
        // submit 就是消息，消息的分布式id 就是消息的id
        rabbitTemplate.convertAndSend(RabbitMQConstants.SMS_PRE_SEND,submit
        ,new CorrelationData(submit.getSequenceId().toString()));

        return R.ok();

    }

    @Value("${headers}")
    private String headers;
    private final String UNKNOW="unknow";
    private final String X_Forwarded_For="X-Forwarded-For";
    private final String X_Real_Ip="x-real-ip";

    /**
     * 获取真实IP
     *
     * @param request
     * @return 真实ip
     */
    private String getRealIP(HttpServletRequest request) {


        String ip;
        //遍历headrs
        for (String header: headers.split(",")) {
            //健壮性校验
            if (!StringUtils.isEmpty(request.getHeader(header))){
                //如果是 X-Forwarded-For 只取第一个
                if (X_Forwarded_For.equals(header)){
                    ip= headers.substring(0,1);
                    log.info("通过 X_Forwarded_For 获取到了真实IP，ip={}",ip);
                    return ip;
                }
                //获取ip
                ip=request.getHeader(header);
                if (!StringUtils.isEmpty(ip)&& !UNKNOW.equalsIgnoreCase(ip)){
                    log.info("通过X_Real_Ip 获取到了真实IP，ip={}",ip);
                    return ip;
                }
            }
        }
        return request.getRemoteAddr();
    }
}


